var mysql = require('./mysql/mysql');
var logger = require('pomelo-logger').getLogger(__filename);
var userdao = module.exports;

userdao.getUserByName = function (username, cb){
    var sql = 'select * from user where username = ?';
    var args = [username];
    mysql.query(sql,args,function(err, res){
        if(err !== null){
            cb(err.message, null);
        } else {
            if (!!res && res.length === 1) {
                var rs = res[0];
                var user = {id: rs.uid, name: rs.name, password: rs.password};
                cb(null, user);
            } else {
                cb(' user not exist ', null);
            }
        }
    });
};
//登陆时判断用户名和密码是否对应
userdao.confirmUser = function (username,password, cb){
    var sql = 'select * from user where username = ? and password = ?';
    // var args = [username];
    var args = [username,password];
    mysql.query(sql,args,function(err, res){
        if(err !== null){
            cb(err.message, null);
        } else {
            if (!!res && res.length === 1) {
                var rs = res[0];
                var user = {id: rs.uid, name: rs.name, password: rs.password};
                cb(null, user);
            } else {
                cb(' user not exist ', null);
            }
        }
    });
};

userdao.createUser = function (username, password, cb){
    var sql = 'insert into user (username,password) values(?,?)';
    var args = [username, password];
    mysql.insert(sql, args, function(err,res){
        if(err !== null){
            cb({code: err.number, msg: err.message}, null);
        } else {
            // var userId = res.insertId;
            var user = {id: res.insertId, name: username, password: password};
            cb(null, user);
        }
    });
};

